<?php

namespace App\Console\Commands;

use App\Models\TsExportModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\depository\TsOrderDep;

class ExportCmd extends Command
{
    //生成文件
    public $signature = 'order:export';

    public function handle()
    {

        $this->info('ok');

        $orderDep = new TsOrderDep();

        $task = TsExportModel::where('status', 1)->get();
        if ($task->isEmpty()) {
            $this->log('没有待执行任务');
            return false;
        }

        $config = ['path' => storage_path("/app/public/")];

        $task->each(function ($item) use ($orderDep,$config) {

            $this->info("开始处理，{$item->token}");
            TsExportModel::where('id',$item->id)->update(['status' => 2]);

            $param = [
              "province" => $item->province,
              "city" => $item->city,
              "limit" => $item->limit,
            ];
            $resOrder =  $orderDep->apiList($param);
            if($resOrder->isEmpty()){
                $this->log("未查询到订单");
            }

            $excelData = [];
            $resOrder->map(function($item) use (&$excelData){

                $excelData[] = [
                  $item->name,$item->orderid,$item->getprovince,$item->getcity
                ];
            });

            $excel = new \Vtiful\Kernel\Excel($config);
            $filePath = $excel->fileName("{$item->token}.xlsx")
                ->header(['name', 'orderid','getprovince','getcity'])
                ->data($excelData)
                ->output();

            $resOrder->each(function($item) use ($orderDep){
                $orderDep->upd($item->id,['count' => $item->count - 1]);
            });

            $this->info("处理完成, {$filePath}");
            TsExportModel::where('id',$item->id)->update(['status' => 3]);
        });

        $this->info("处理完成,{$this->getMemoryUsage()}");
    }

    public function log($message)
    {
        $this->info($message);
        Log::info($message);
    }

    function getMemoryUsage($precision = 2)
    {
        $size = memory_get_usage(true);

        $unit = ['b', 'kb', 'mb', 'gb', 'tb', 'pb'];

        return round($size / pow(1024, ($i = floor(log($size, 1024)))), $precision) . ' ' . $unit[$i];
    }

}
